package tw.asap.plus.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Created by chenfeiyue on 15/7/28.
 */
public class Utils {

    private static String sID = "";
    private static final String UNIQUEID = "UNIQUEID";

    public static String getAppVersion(Context context) {
        String appVersion ="1.0";
        try {
            appVersion = context
                    .getPackageManager()
                    .getPackageInfo(
                            context.getPackageName(), 0).versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return appVersion;
    }

    public static String getFormatAmt(String amt) {
        String formatAmt = "";
        try {
            formatAmt = String.format("%d", Integer.parseInt(amt) / 100);
        } catch (Exception e) {
            T.e(e.toString());
        }
        return formatAmt;
    }

    public static void onCopy2Clipboar(Context context, String text) {

        if (android.os.Build.VERSION.SDK_INT > 11) {
            ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setPrimaryClip(ClipData.newPlainText("text", text));
        } else {
            android.text.ClipboardManager cmb = (android.text.ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(text);
        }
    }


    public static String getDeviceId(Context context) {
        if (context == null) {
            return "";
        }
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = "";

        try {
            deviceId = telephonyManager.getDeviceId();
        }catch (Exception e){
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(deviceId)) {
            try {
                deviceId = telephonyManager.getSimSerialNumber();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (TextUtils.isEmpty(deviceId)) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            String macAddress = wifiManager.getConnectionInfo().getMacAddress();
            deviceId = md5(macAddress);
        }
        if (TextUtils.isEmpty(deviceId)) {
            try {
                deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(TextUtils.isEmpty(deviceId)){
            deviceId = md5(uniqueId(context));
        }
        return deviceId;
    }

    private static String md5(String plainText) {
        if (TextUtils.isEmpty(plainText)) {
            return "";
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
//            System.out.println("result: " + buf.toString());//32位的加密
//            System.out.println("result: " + buf.toString().substring(8,24));//16位的加密
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public synchronized static String uniqueId(Context context) {
        if (sID == null) {
            File uniqueid = new File(context.getFilesDir(), UNIQUEID);
            try {
                if (!uniqueid.exists())
                    writeUniqueidFile(uniqueid);
                sID = readUniqueidFile(uniqueid);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }


    private static String readUniqueidFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeUniqueidFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }

}
